let srcs = document.scripts[document.scripts.length - 1].src.split('/');
window.appRoot = srcs.slice(0, -2).join('/') + '/';
window.baseRoot = srcs.slice(0, -1).join('/') + '/';
window.tapiRoot = window.taAdmin || window.appRoot + "index";

/*! 挂载 layui & jquery 对象 */
layui.config({base: baseRoot + 'plugs/layui_exts/'});
window.form = layui.form, window.layer = layui.layer;
window.laytpl = layui.laytpl, window.laydate = layui.laydate;
window.jQuery = window.$ = window.jQuery || window.$ || layui.$;

// 封装通用的 AJAX 请求方法
window.ajaxRequest = function (url, data, method = 'GET', buttonElement, successCallback, errorCallback) {
    // 禁用按钮并更改样式
    if (buttonElement) {
        $(buttonElement).prop('disabled', true).css('background-color', '#ccc');
    }

    $.ajax({
        url: url,
        type: method,
        data: data,
        dataType: 'json',
        success: function (response) {
            if (response.code === 200) {
                // 请求成功且 code 为 1 时处理
                if (typeof successCallback === 'function') {
                    successCallback(response);
                } else {
                    console.log('Request succeeded:', response.data);
                }
            } else {
                // 请求失败或 code 不为 200 时处理
                if (typeof errorCallback === 'function') {
                    errorCallback( response.msg  || response);
                } else {
                    layer.msg(response.msg || 'Request failed. Please try again later.', {icon: 5}); // 使用 layer 弹出错误信息
                }
            }
        },
        error: function (xhr, status, error) {
            // AJAX 请求本身出错的处理
            if (typeof errorCallback === 'function') {
                errorCallback(status, error);
            } else {
                console.error('Request failed:', status, error);
                layer.msg('Request failed. Please try again later.', {icon: 5}); // 使用 layer 弹出通用错误信息
            }
        },
        complete: function () {
            // 恢复按钮状态
            if (buttonElement) {
                $(buttonElement).prop('disabled', false).css('background-color', '');
            }
        }
    });
};


